package com.interfaces.module.user.controller;

import com.baomidou.mybatisplus.extension.service.IService;
import com.interfaces.config.RedisCache;
import com.interfaces.enumeration.HTTP_STATUS_CODE_ENUM;
import com.interfaces.enumeration.TOKEN_TYPE;
import com.interfaces.module.common.controller.CommonController;
import com.interfaces.module.user.domain.FtsUser;
import com.interfaces.module.user.service.FtsUserService;
import com.interfaces.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class FtsUserController extends CommonController<FtsUser> {
    @Autowired
    private FtsUserService ftsUserService;
    @Override
    protected IService<FtsUser> getCoreService() {
        return ftsUserService;
    }
    @Autowired
    RedisCache cache;
    @RequestMapping("/getUser")
    public Result getUser(HttpServletRequest request){
        String token=request.getHeader(TOKEN_TYPE.TOKEN.name());
        StringBuffer tokenStr=new StringBuffer(TOKEN_TYPE.TOKEN.getValue());
        tokenStr.append(token);
        FtsUser ftsUser=cache.getCacheObject(tokenStr.toString());

        if(null==ftsUser){
            return Result.ERROR(HTTP_STATUS_CODE_ENUM.TOKEN_NOT_FIND);
        }
        FtsUser resultUser=ftsUserService.getById(ftsUser.getId());
        resultUser.setToken(tokenStr.toString());
        return Result.SUCCESS(resultUser);
    }
    @PostMapping("/logout")
    public Result logout(HttpServletRequest request){
        String token=request.getHeader(TOKEN_TYPE.TOKEN.name());
        StringBuffer tokenStr=new StringBuffer(TOKEN_TYPE.TOKEN.getValue());
        tokenStr.append(token);
        FtsUser ftsUser=cache.getCacheObject(tokenStr.toString());
        ftsUser.setState(2);
        ftsUserService.updateById(ftsUser);
        cache.deleteObject(tokenStr.toString());
        return Result.SUCCESS("注销成功");
    }

    @PostMapping("/exitLogin")
    public Result exitLogin(HttpServletRequest request){
        String token=request.getHeader(TOKEN_TYPE.TOKEN.name());
        StringBuffer tokenStr=new StringBuffer(TOKEN_TYPE.TOKEN.getValue());
        tokenStr.append(token);
        cache.deleteObject(tokenStr.toString());
        return Result.SUCCESS("退出成功");
    }
}
